
'''
png_convert_word.py
解析png图片中的单词
'''
import requests
import base64
from pdf_convert_png import reload_fileNames
from setting import SK, AK
from setting import pdf_path, image_path
import easyocr
import enchant
word_list = []

import re
def filter_str(desstr, restr=''):
    # 过滤除中英文及数字以外的其他字符
    # res = re.compile("[^\\u4e00-\\u9fa5^a-z^A-Z^0-9]")
    res = re.compile("[^\\u4e00-\\u9fa5^a-z^A-Z]") # 只保留字母
    return res.sub(restr, desstr)

# 1.调用鉴权接口获取token
# client_id 为官网获取的AK， client_secret 为官网获取的SK
def get_token(ak, sk):  # 有效日期为30天
    token = ""
    host = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + \
        AK+"&client_secret="+SK
    print("host:"+host)
    response = requests.get(host)
    if response:
        # print(response.json())
        token = response.json()
        token = token['access_token']
    elif(response.status_code == 400):
        print("获取token失败，请检查AK和SK是否过期")
    return token
# 二进制方式打开图片文件


def png_convert_json(token, filename):
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
    f = open(filename, 'rb')
    img = base64.b64encode(f.read())
    params = {"image": img}
    access_token = token
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        return response.json()  # 返回识别json结果
        #print (response.json())


def png_convert_word(file_name, file_path):  # 传入文件路径和文件名
    global word_list
    # print("..................解析图片为单词开始..................");
    token = get_token(AK, SK)
    print(token)
    # 2020年2月23日00:52:00 token = 24.e1aea6**e***e532c.2**2000.158498**44.28233**-18**149
    # token = "24.e****69d2f691b534e885e62***ce532c.2592000.1584982244.282335-18553149";
    #file_name = "../png/1-images_0.png";
    complete_path = file_path+"/"+file_name
    print("当前操作文件:{}".format(complete_path))

    png_json = png_convert_json(token, complete_path)
    # json文件 words_result_num 检测数量 words_result['words'] 检测结果
    # print("识别数量:",png_json['words_result_num']);
    print(png_json)
    for i in png_json['words_result']:
        flag_index = i['words'].find('[')
        # 过滤出单词
        # 字符串查找[符号获得下表后使用字符串切片
        # 过滤掉除了英文的东西
        if flag_index != -1 and i['words'][:flag_index].isalpha():
            print(i['words'][:flag_index])
            word_list.append(i['words'][:flag_index])
    # print("识别单词个数:{}".format(len(word_list)));
    print(word_list)
    # return word_list


def png_easyocr_convert_word(file_name, file_path):
    global word_list
    complete_path = file_path+"/"+file_name
    print("当前操作文件:{}".format(complete_path))

    reader = easyocr.Reader(['en'])
    result = reader.readtext(complete_path)
    # print(result)
    for i in result:
        word = i[1]
        word_list += sentence_convert_word(word)

    print(word_list)

# if __name__ == "__main__":
#     png_files = reload_fileNames(image_path,'png')
#     #print(png_files);
#     for png_file_name in png_files:
#         png_convert_word(png_file_name,image_path);
#         #input();
#     print("识别单词个数:",len(word_list));
#     print(word_list);


def sentence_convert_word(p):
    mDict = enchant.Dict("en_US")
    words = []  # 建立一个空列表
    index = 0   # 遍历所有的字符
    start = 0   # 记录每个单词的开始位置
    while index < len(p):   # 当index小于p的长度
        start = index       # start来记录位置
        while p[index] != " " and p[index] not in [".", ","]:   # 若不是空格，点号，逗号
            index += 1   # index加一
            if index == len(p):  # 若遍历完成
                break   # 结束
        w = filter_str(p[start:index])
        if w != "":
            if mDict.check(w):
                words.append(w)
        # words.append(p[start:index])
        if index == len(p):
            break
        while p[index] == " " or p[index] in [".", ",", "#"]:
            index += 1
            if index == len(p):
                break

    return words
